<template>
  <b-container fluid style="font-size: 0.9rem;">
    <!-- 导航布局 -->
    <b-row>
      <b-col>
        <div style="margin-bottom:10px;float: right;">
          <b-input-group>
            <slot name="button-operation">
              <b-button size="sm" variant="outline-primary" style="margin-right:6px" @click="create">
                新建
              </b-button>
              <b-button size="sm" variant="outline-primary" style="margin-right:6px" @click="batchRemove">
                批量删除
              </b-button>
            </slot>
          </b-input-group>
        </div>
      </b-col>
      <div class="w-100"></div>
      <b-col>
        <b-form-group horizontal style="width:50%;float:right">
          <div>
            <b-input-group-append style="float: right;">
              <b-button size="sm" variant="outline-success" style="margin-right:10px" @click="$refs.table.refresh()">
                <i class="icon ion-refresh"></i>
                刷新
              </b-button>
              <b-input-group size="sm" prepend="字段">
                <b-form-select v-if="table.searchTool.options.length>0" v-model="table.searchTool.selected" :options="table.searchTool.options"></b-form-select>
              </b-input-group>
              <b-form-input class="mr-sm-2" v-model="table.searchTool.value" size="sm" style="width: auto;float: left;" placeholder="Type to Search" />
              <b-btn size="sm" class="my-2 my-sm-0" :disabled="!table.searchTool.value" @click="search()">搜索</b-btn>
            </b-input-group-append>
            </b-input-group>
          </div>
        </b-form-group>
      </b-col>
    </b-row>
    <!-- Main table element -->
    <b-table :api-url="`${location}?${param}`" ref="table" striped bordered :fixed="fixed" :busy.sync="table.isBusy" small outlined show-empty stacked="md" :items.sync="onTableDataProvider" :fields="table.fields" :current-page="table.currentPage" :per-page="table.perPage" :filter="table.filter" :sort-by.sync="table.sortBy" :sort-desc.sync="table.sortDesc" :sort-direction="table.sortDirection" @filtered="onFiltered">
      <template slot="associate" slot-scope="row">
        <b-form-checkbox @click.native.stop @change="onToggleTableSelect(row)" v-model="row.item.selected"> </b-form-checkbox>
      </template>
      <template slot="operation" slot-scope="row">
        <slot name="table-operation" :data="row"></slot>
      </template>
      <template v-for="filterField in filterFields" :slot="filterField" slot-scope="row">
        <slot :name="`table-${filterField}`" :data="row"></slot>
      </template>
    </b-table>
    <!-- 表尾部 -->
    <div style="margin-left: 0px;">
      <div class="pages-number" style="display:flex;float:left">
        <span style="height: 20px;margin-top: 7px;margin-right: 5px;">显示第 1 到第 {{table.perPage}} 条记录，总共 {{table.totalRows}} 条记录每页显示</span>
        <b-form-group>
          <b-form-select :options="table.pageOptions" v-model="table.perPage" />
        </b-form-group>
        <span style="height: 20px;margin-top: 7px;margin-left:5px">条记录</span>
      </div>
      <b-pagination style="float: right;" :total-rows="table.totalRows" :per-page="table.perPage" v-model="table.currentPage" />
    </div>
    <!-- Info modal -->
    <InfoModal ref="InfoModal" v-on:update="$refs.table.refresh()" :location="location"></InfoModal>
  </b-container>
</template>
<script>
import { mapGetters } from "vuex";
import InfoModal from "./InfoModal.vue";
import basic from "@/mixins/basic";
import {
  baseURL,
  get,
  save,
  associate,
  associateByPut,
  getAndAssociate,
  remove,
  update,
  axios
} from "@/service/api";
// 表格：功能有过滤,排序，limit等功能默认都是未开启的
export default {
  name: "info-table",
  mixins: [basic],
  components: {
    InfoModal
  },
  props: {
    href: {
      type: String,
      default: () => null
    },
    location: {
      type: String,
      default: () => null
    },
    param: {
      type: String,
      default: () => ""
    },
    filterFields: {
      type: Array,
      default: () => []
    },
    fixed: {
      type: Boolean,
      default: () => true
    }
  },
  data() {
    return {
      table: {
        searchTool: {
          selected: null,
          options: [],
          value: ""
        },
        isBusy: false,
        current: {
          record: {}
        },
        selected: [],
        items: [],
        fields: [],
        currentPage: 1,
        perPage: 5,
        totalRows: 0,
        pageOptions: [5, 10, 15],
        sortBy: null,
        sortDesc: false,
        sortDirection: "asc",
        filter: null
      }
    };
  },
  mounted() {
    if (this.href != null) {
      for (let i = 0; i < this.entry.items.length; i++) {
        if (this.entry.items[i].location == this.href) {
          this.table.fields = JSON.parse(
            JSON.stringify(this.entry.items[i].table.fields)
          );
          break;
        }
      }
    } else {
      for (let i = 0; i < this.entry.items.length; i++) {
        if (this.entry.items[i].location == this.getLocation(this.location)) {
          this.table.fields = JSON.parse(
            JSON.stringify(this.entry.items[i].table.fields)
          );
          // 将字段转换为搜索的字段
          this.table.fields.forEach(e => {
            this.table.searchTool.options.push({
              text: e.label,
              value: e.key
            });
          });
          break;
        }
      }
    }
  },
  methods: {
    batchRemove() {
      if (this.table.selected.length <= 0) {
        alert("未选择记录");
      } else {
        let msg = "您真的确定要删除吗？\n\n请确认！";
        if (confirm(msg) == true) {
          let self = this;
          console.log(this.table.selected);
          let removes = [];
          let removeIndexs = [];
          this.table.selected.forEach(element => {
            removes.push(
              remove(`${this.getLocation(this.location)}/${element}`)
            );
            removeIndexs.push(element);
          });
          axios.all(removes).then(
            axios.spread(function(result) {
              // 请求现在都执行完成
              if (result.status == "204") {
                console.log("资源删除成功");
                alert("资源删除成功");
                self.refresh();
                self.table.selected = [];
              }
              console.log(result);
            })
          );
          return true;
        } else {
          return false;
        }
      }
    },
    create() {
      this.$refs.InfoModal.create();
    },
    info(record) {
      this.table.current.record = record;
      this.$refs.InfoModal.info(record);
    },
    batchAddAssociate(href, record) {
      let self = this;
      console.log(this.table.selected);
      let removes = [];
      let removeIndexs = [];
      this.table.selected.forEach(element => {
        console.log(`${this.getLocation(this.location)}/${element}/${record}`);
        console.log(href);
        removes.push(
          associate(
            `${this.getLocation(this.location)}/${element}/${record}`,
            href
          )
        );
        removeIndexs.push(element);
      });
      axios.all(removes).then(
        axios.spread(function(result) {
          // 请求现在都执行完成
          if (result.status == "204") {
            console.log("关联添加成功");
            alert("关联添加成功");
            self.refresh();
          }
          console.log(result);
        })
      );
    },
    addAssociate(href, record) {
      let self = this;
      associate(record, href)
        .then(response => {
          if (response.status == "204") {
            console.log("关联添加成功");
            alert("关联添加成功");
            self.refresh();
          }
        })
        .catch(error => {
          console.log("添加关联失败");
        });
    },
    batchRemoveAssociate(href, record) {
      let self = this;
      let msg = "您真的确定要删除吗？\n\n请确认！";
      if (confirm(msg) == true) {
        console.log(this.table.selected);
        let removes = [];
        let removeIndexs = [];
        this.table.selected.forEach(element => {
          removes.push(
            associateByPut(
              `${this.getLocation(this.location)}/${element}/${record}`,
              this.alterKey(href, "0")
            )
          );
          removeIndexs.push(element);
        });
        axios.all(removes).then(
          axios.spread(function(result) {
            // 请求现在都执行完成
            if (result.status == "204") {
              console.log("关联删除成功");
              alert("关联删除成功");
              self.refresh();
              self.table.selected = [];
            }
            console.log(result);
          })
        );
        return true;
      } else {
        return false;
      }
    },
    removeAssociate: async function(href, record) {
      let self = this;
      let msg = "您真的确定要删除吗？\n\n请确认！";
      if (confirm(msg) == true) {
        return new Promise((resolve, reject) => {
          associateByPut(record, this.alterKey(href, "0"))
            .then(response => {
              if (response.status == "204") {
                console.log("关联删除成功");
                alert("关联删除成功");
                self.refresh();
                resolve(true);
                self.table.selected = [];
              }
            })
            .catch(error => {
              console.log("删除关联失败");
            });
        });
      } else {
        return false;
      }
    },
    remove(record) {
      let self = this;
      let msg = "您真的确定要删除吗？\n\n请确认！";
      if (confirm(msg) == true) {
        console.log(record);
        remove(record.item._links.self.href)
          .then(response => {
            if (response.status == "204") {
              console.log("资源删除成功");
              alert("资源删除成功");
              self.refresh();
            }
            console.log(response);
          })
          .catch(error => {
            console.log("资源删除失败");
            console.log(error);
          });
        return true;
      } else {
        return false;
      }
    },
    // 刷新表格的数据
    refresh() {
      console.log("刷新");
      this.$refs.table.refresh();
      this.table.selected = [];
    },
    onFiltered(filteredItems) {
      // Trigger pagination to update the number of buttons/pages due to filtering
      this.table.totalRows = filteredItems.length;
      this.table.currentPage = 1;
    },
    // 是否选择事件
    onToggleTableSelect(entry) {
      // 获取记录的主键
      let key = parseInt(this.getKey(entry.item._links.self.href));
      // 有则删除,没有则添加
      this.table.selected.includes(key)
        ? (this.table.selected = this.table.selected.filter(n => n !== key))
        : this.table.selected.push(key);
    },
    // 初始化提供数据
    onTableDataProvider(ctx) {
      let self = this;
      let location = this.location;
      let page = `page=${ctx.currentPage - 1}`;
      let size = `size=${ctx.perPage}`;
      let sort = `sort=${this.getSort(location, ctx.sortBy)},${
        ctx.sortDesc ? "desc" : "asc"
      }`;
      if (this.param != "") {
        location = `${location}?${this.param}&${page}&${size}&${sort}`;
      } else {
        location = `${location}?${page}&${size}&${sort}`;
      }
      if (
        this.table.filter != null ||
        this.table.filter != "" ||
        typeof this.table.filter != undefined
      ) {
        location = `${location}&${this.table.searchTool.selected}=${
          this.table.filter
        }`;
      }
      console.log(location);
      return get(location)
        .then(response => {
          if (response.status == "200") {
            if (response.data._embedded) {
              console.log(this.getLocation(this.location));
              const items =
                response.data._embedded[this.getLocation(this.location)];
              items.forEach(element => {
                let key = parseInt(this.getKey(element._links.self.href));
                if (self.table.selected.includes(key)) {
                  element.selected = true;
                }
              });
              console.log("返回结果");
              console.log(response);
              self.table.totalRows = response.data.page.totalElements;
              return items;
            } else {
              const items = [response.data];
              self.table.totalRows = 1;
              return items;
            }
          }
        })
        .catch(error => {
          console.log(error);
          return [];
        });
    },
    search() {
      // 解决中文乱码问题
      this.table.filter = encodeURI(encodeURI(this.table.searchTool.value));
      this.table.searchTool.value = "";
    }
  },
  computed: {
    ...mapGetters({
      entry: "entry"
    }),
    sortOptions() {
      // Create an options list from our fields
      return this.table.fields.filter(f => f.sortable).map(f => {
        console.log("排序");
        return { text: f.label, value: f.key };
      });
    }
  },
  watch: {
    param: function() {
      console.log("pros执行了");
      this.refresh();
    }
  }
};
</script>
<style lang="scss" scoped>
.table th,
.table td {
  vertical-align: middle;
}
.custom-select {
  float: right;
}
</style>
